package com.qingke.qixi.command_impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.qingke.qixi.App;
import com.qingke.qixi.Console;
import com.qingke.qixi.IDao.InterestMapper;
import com.qingke.qixi.command.Command;
import com.qingke.qixi.pojo.Interest;
import com.qingke.qixi.pojo.User;

public class EditCommand extends Command {

	@Override
	public void execute() {
		
		if(App.getInstance().getCurrentUser()==null) {
			Console.println("您还未登录");
			return;
		}
		
		User currentUser = App.getInstance().getCurrentUser();

		Console.println("代表性地实现更改【兴趣】的功能");
		
		
		List<Interest> interests = currentUser.getInterests();
		listInterests(interests);
		int edit = Console.askInputInt("请输入要更新的兴趣信息编号");
		while (true) {
			if (edit >= 1 && edit <= interests.size()) {
				break;
			}
			edit = Console.askInputInt("编号不正确，请重新输入");
		}
		
		Interest interest = editInterest(interests.get(edit - 1));

		SqlSession session = getSession();
		InterestMapper interestMapper = session.getMapper(InterestMapper.class);
		interestMapper.insertSelective(interest);
		session.commit();
	}

	private Interest editInterest(Interest interest) {
		// TODO Auto-generated method stub
		Console.println("请输入更改后的新信息，名字输入为空或喜爱程度输入为0表示不更改");
		String name = Console.askInput("新的兴趣名");
		if (!"".equals(name.replaceAll(" ", ""))) {
			interest.setName(name);
			Console.println("兴趣名已成功更改为" + name);
		} else {
			Console.println("兴趣名没有发生变化");
		}
		int level = Console.askInputInt("新的兴趣喜爱程度");
		while (true) {
			if (level < 0 || level > 10) {
				level = Console.askInputInt("喜爱程度的范围为1-10，输入0表示不变");
			} else if (level != 0) {
				interest.setLevel(level);
				Console.println("喜爱程度已成功更改为" + level);
				break;
			}else {
				Console.println("喜爱程度没有发生变化");
				break;
			}
		}
		return interest;
	}

	private void listInterests(List<Interest> interests) {
		if (interests.size() < 1) {
			Console.println("您还没有添加兴趣");
			return;
		}
		int i = 1;
		Console.println("您的所有兴趣:");
		for (Interest interest : interests) {
			Console.print("【" + i + "】");
			Console.println(interest);
			i++;
		}
	}
}
